<?php
if (!defined('TB_CATEGORIES')){ define('TB_CATEGORIES','categories');}
require_once(LIB.'/class_Categories.php');
class administration_controller {
    
    private $categories;
    private $structure;
    function __construct() {
        $this->fetch_data();
    }
    
    function fetch_data(){
        $categories=new categories();
        $categories->get_full_list();
        $cat_structure=$categories->open_categories_tree(0,0);
        array_shift($cat_structure);   
        $this->structure=$cat_structure;
        $this->categories=$categories->categories;                
    }
    //------------------------------------category-------------------------------------------------
    public function exec_view_category(){

        $data = array('category_name'=>'', 'parent_id'=>0,'category_priority'=>0,);
        $content = '<h1 style="margin:10px">Category Management</h1>';
        $content .= $this->show_create_form1($data);        
        $content .= $this->show_list();
        
        $posts_tpl = new Template(MODULE_ROOT.'/administration/view/view_category.html');

        //$m_content=$posts_tpl->fetch();
        $m_content=$content;
        $menu = $this->show_left_menu();

        $tpl = new Template(MODULE_ROOT.'/administration/view/layout.html');
        $tpl ->set('left_menu', $menu);
        $tpl ->set('content', $m_content);

        //print_r($m);
        $content1 = $tpl ->fetch();
        return array('content'=>$content1);

    
    }
    public function exec_edit_category(){
        //This function edit a category
        $status = GET_value('s');
        $category_id = (int) GET_value('category_id',0);
        $data =array();
        $excluded_ids = $this->categories[$category_id]['descendants'];
        array_push($excluded_ids, $category_id); // Cannot set parent id to the current ID or children's ID!
        
        if ('submit' == $status){
            $data['category_id'] =  $category_id;
            $data['category_name'] =  POST_value('category_name','');
            $data['category_u_name'] = VN_unaccent($data['category_name']);
            $data['parent_id'] = (int) POST_value('parent_id',0);
            $data['category_priority'] = (int) POST_value('category_priority',0);
            $data['excluded_ids']=$excluded_ids;
            $r = Categories :: update($data);
            if ($r['success']){
                $content='<div class="success" style="margin:10px">Update successfully!</div>';
                $this->fetch_data();
                $index = $this->exec_view_category();
                $content.=$index['content'];
            }else{
                $content = $this->show_edit_category($data, $r['error']);
            }
        }else{
            //Just show form
            $r = Categories :: get_category($category_id);
            if (!$r['success']){
                $content = '<div class="error">'.$r['error'].'</div>';                                
            }else{
                $data=$r['data'];
                $data['excluded_ids']=$excluded_ids;
                $content = $this->show_edit_category($data, null);                
            }
        }
        
        return array('content'=>$content);
    }
    private function show_edit_category($data,$error=''){
        $tpl = new Template(MODULE_ROOT.'/admin_categories/view/edit_form.html');
        $tpl->set('categories',$this->categories); 
        $tpl->set('structure',$this->structure); 
        $tpl->set('data',$data); 
        $tpl->set('error',$error); 
        return $tpl ->fetch();        
    }
    
   private function show_list(){
        $tpl = new Template(MODULE_ROOT.'/admin_categories/view/index.html');
        $tpl->set('categories',$this->categories); 
        $tpl->set('structure',$this->structure); 
        return $tpl ->fetch();        
    }
    
    private function show_create_form1($data,$error=''){
        $tpl = new Template(MODULE_ROOT.'/admin_categories/view/create_form.html');
        $tpl->set('categories',$this->categories); 
        $tpl->set('structure',$this->structure); 
        $tpl->set('data',$data); 
        $tpl->set('error',$error); 
        return $tpl ->fetch();        
    }
    
   public function exec_create_category(){
        //This function create a new users
        $status = GET_value('s');
        $data['category_name'] =  POST_value('category_name','');
        $data['category_u_name'] = VN_unaccent($data['category_name']);
        $data['parent_id'] = (int) POST_value('parent_id',0);
        $data['category_priority'] = (int) POST_value('category_priority',0);
        if ('submit' == $status){
            $r = Categories :: create($data);
            if ($r['success']){
                $content='<div class="success" style="margin:10px">Group '.$data['category_name'].' is successfully created</div>';
                $this->fetch_data();
                $index = $this->exec_view_category();
                $content.=$index['content'];
            }else{
                $content = $this->show_create_form($data, $r['error']);
            }
        }else{
            //Just show form
            $content = $this->show_create_form($data, null);
        }
        
        return array('content'=>$content);
    }
   //----------------------------end catagory------------------------------------------------------ 
    public function exec_index(){
        global $dbdefault;
        $m =  GET_value('m','administration');
        $s =  GET_value('se','');
        
        $item_per_page = 20;        
        $page_num = GET_value('p',1);
        $limit = ($page_num-1)*$item_per_page;
        $offset = $item_per_page+1;
        
        
        if($s==''){
            $qry="SELECT count(*) AS total FROM users"; 
            $query = "SELECT * FROM users order by user_name LIMIT $limit, $offset";
        }else{
            $qry="SELECT count(*) AS total FROM users where user_name like '%$s%'"; 
            $query = "SELECT * FROM users where user_name like '%$s%' order by user_name LIMIT $limit, $offset";
        }
        
        $res_total=mysql_query($qry,$dbdefault) or die(mysql_error()."<br />".$qry);
        $total=mysql_result($res_total,0,'total');
        $num_pages=ceil($total/$item_per_page);
        
        $result = mysql_query($query,$dbdefault) or die(__CLASS__."->".__METHOD__.": ".mysql_err());
        $users=array();
        while($r = mysql_fetch_assoc($result)){
            $users[]=$r;
        }

        $posts_tpl = new Template(MODULE_ROOT.'/administration/view/view_user.html');
        $posts_tpl ->set('users', $users);
        $posts_tpl->set('page_num', $page_num);
        $posts_tpl->set('num_pages', $num_pages);
        $posts_tpl->set('s', $s);

        $m_content=$posts_tpl->fetch();
        $menu = $this->show_left_menu();

        $tpl = new Template(MODULE_ROOT.'/administration/view/layout.html');
        $tpl ->set('left_menu', $menu);
        $tpl ->set('content', $m_content);
        $tpl ->set('m', $m);
        //print_r($m);
        $content = $tpl ->fetch();
        return array('content'=>$content);
    }
    
  public function exec_create_user(){
      global $dbdefault;
      $status = GET_value('s');
        $data['user_name'] = strtolower (POST_value('user_name',''));
        $data['user_password'] = POST_value('user_password','');
        $data['user_password1'] = $data['user_password'];
        $data['user_email'] = strtolower (POST_value('user_email',''));
        $data['user_realname'] = POST_value('user_realname','');
        $data['group_id'] = POST_value('group_id',0);
        

        
        if ('submit' == $status){
            //Do insert stuff
            $query=  sprintf("SELECT idcustomer FROM groups WHERE group_id=%d",  $data['group_id']);
            $res_total=mysql_query($query,$dbdefault) or die(mysql_error()."<br />".$query);
            $idcustomer=mysql_result($res_total,0,'idcustomer');
            
            $data['idcustomer']=$idcustomer;
            $r = User :: create($data);
            if ($r['success']){
                $content='<div class="success" style="margin:10px">User '.$data['user_name'].' is successfully created</div>';
                $index = $this->exec_index();
                $content.=$index['content'];
            }else{
                $content = '';
                if (!empty($r['error'])){ 
                    $content = '<div class="error" style="margin:10px">'.$r['error'].'</div>';
                }
                $content .= $this->show_create_form($data, $r['form_error']);
            }
        }else{
            //Just show form
            $content = $this->show_create_form($data, null);
        }
        
        return array('content'=>$content);
  }
    
   public function exec_edit_user(){
        global $dbdefault;
       $m =  GET_value('m','administration');
      $status = GET_value('s');
        $user_id = (int) GET_value('user_id',0);
        
        if ('submit' == $status){
            $data['user_id'] = $user_id; 
            $data['user_name'] = POST_value('user_name','');
            $data['user_password'] = POST_value('user_password','');
            $data['user_password1'] = $data['user_password'];
            $data['user_email'] = strtolower (POST_value('user_email',''));
            $data['user_realname'] = POST_value('user_realname','');
            $data['group_id'] = POST_value('group_id',0);
            $data['status'] = POST_value('status',0);
            
            $query=  sprintf("SELECT idcustomer FROM groups WHERE group_id=%d",  qs($data['group_id']));
            $res_total=mysql_query($query,$dbdefault) or die(mysql_error()."<br />".$query);
            $idcustomer=mysql_result($res_total,0,'idcustomer');
            if($idcustomer){
                $data['idcustomer']=$idcustomer;
            }else{
                $data['idcustomer']=0;
            }
            
            $r = User :: update($user_id,$data);
            if ($r['success']){
                $content = '<div class="success">Update successful!</div>';
                //$index = $this->exec_index();
                header('Location: index.php?m=administration');
                //$content.=$index['content']; 
            }else{
                $content='';
                if (isset($r['error'])) $content .= '<div class="error">Something wrong! '.$r['error'].'</div>';
                $content .= $this->show_edit_form($data, $r['form_error']);
            }
        }else{
            $r = User :: get_user_data($user_id);
            if ($r['success']){
                $content = $this->show_edit_form($r['data'], null);
            }else{
                $content = $this->exec_error($r['error']);
            }
        }
        return array('content' => $content);
  }
  
  public function exec_delete_user(){
      $user_id = (int) GET_value('user_id',0);

        $r = User :: delete($user_id);
        if ($r['success']){
            $content = '<div class="success">Delete user successful!</div>';
            $index = $this->exec_index();
            $content.=$index['content']; 
        }else{
            $content='';
            if (isset($r['error'])) $content .= '<div class="error">Something wrong! '.$r['error'].'</div>';
            $index = $this->exec_index();
            $content .= $index['content'];
        }
        return array('content' => $content);
  }
  


    private function show_left_menu($action=''){
//        global $dbdefault;
//        //Get number of user posts
//        $query = 'SELECT  `status`,count(*) as total FROM `contents` 
//            WHERE `user_id`='.SESSION_value('user_id').' GROUP BY `status` ';
//        $res = mysql_query($query,$dbdefault) or die(__CLASS__.'->'.__METHOD__.':'.mysql_error());
//        $posts=array();
//        while($arr = mysql_fetch_assoc($res)){
//            $posts[$arr['status']] = $arr['total'];            
//        }
//        
//        //Get numbers of possts for admins
//        $query = 'SELECT  `status`,count(*) as total FROM `contents` GROUP BY `status` ';
//        $res = mysql_query($query,$dbdefault) or die(__CLASS__.'->'.__METHOD__.':'.mysql_error());
//        $aposts=array();
//        while($arr = mysql_fetch_assoc($res)){
//            $aposts[$arr['status']] = $arr['total'];            
//        }
        
        if (empty($action)) $action =  GET_value('a','index');
        $tpl = new Template(MODULE_ROOT.'/administration/view/left_menu.html');
        $tpl->set('a',$action);
//        $tpl->set('posts',$posts);
//        $tpl->set('aposts',$aposts);
        return $tpl->fetch();
    }
    
    
   private function show_create_form($data,$error){
        $m =  GET_value('m','administration');
        
        
       $posts_tpl = new Template(MODULE_ROOT.'/administration/view/create_form.html');
        $posts_tpl ->set('data', $data);
        $posts_tpl ->set('error', $error);
        //return $tpl ->fetch();
        $m_content=$posts_tpl->fetch();
        $menu = $this->show_left_menu();

        $tpl = new Template(MODULE_ROOT.'/administration/view/layout.html');
        $tpl ->set('left_menu', $menu);
        $tpl ->set('content', $m_content);
        $tpl ->set('m', $m);
        //$content = $tpl ->fetch();
        return $tpl ->fetch();
        //return array('content'=>$content);
    }
    //
    private function show_edit_form($data,$error){
        $m =  GET_value('m','administration');
        
        $posts_tpl = new Template(MODULE_ROOT.'/administration/view/edit_form.html');
        $posts_tpl ->set('data', $data);
        $posts_tpl ->set('error', $error);
        //return $tpl ->fetch();
        $m_content=$posts_tpl->fetch();
        $menu = $this->show_left_menu();

        $tpl = new Template(MODULE_ROOT.'/administration/view/layout.html');
        $tpl ->set('left_menu', $menu);
        $tpl ->set('content', $m_content);
        $tpl ->set('m', $m);
        return $tpl ->fetch();
//        $content = $tpl ->fetch();
//        return array('content'=>$content);
    }
    
 //-----------------------------------Group action ------------------------------------------------------
      public function exec_view_group(){
      
      global $dbdefault;
      $m =  GET_value('m','administration');
        $s =  GET_value('s','');
        
        $item_per_page = 20;        
        $page_num = GET_value('p',1);
        $limit = ($page_num-1)*$item_per_page;
        $offset = $item_per_page+1;
        
        if($s==''){
            $qry="SELECT count(*) AS total FROM groups"; 
            $query = "SELECT a.group_id, a.group_name, a.group_description, b.namecustomer FROM groups a LEFT JOIN customers b ON a.`idcustomer`=b.`idcustomers` order by group_name LIMIT $limit, $offset";
        }else{
            $qry="SELECT count(*) AS total FROM users where user_name like '%$s%'"; 
            $query = "SELECT a.group_id, a.group_name, a.group_description, b.namecustomer FROM groups a LEFT JOIN customers b ON a.`idcustomer`=b.`idcustomers` where group_name like '%$s%' order by group_name LIMIT $limit, $offset";
        }
        //$query = "SELECT a.group_id, a.group_name, a.group_description, b.namecustomer FROM groups a LEFT JOIN customers b ON a.`idcustomer`=b.`idcustomers`";
        
        $res_total=mysql_query($qry,$dbdefault) or die(mysql_error()."<br />".$qry);
        $total=mysql_result($res_total,0,'total');
        $num_pages=ceil($total/$item_per_page);
        
        $result = mysql_query($query,$dbdefault);
        $groups=array();
        while($r = mysql_fetch_assoc($result)){
            $groups[]=$r;
        }

        $posts_tpl = new Template(MODULE_ROOT.'/administration/view/view_group.html');
        $posts_tpl ->set('groups', $groups);
        $posts_tpl->set('page_num', $page_num);
        $posts_tpl->set('num_pages', $num_pages);
        $posts_tpl->set('s', $s);
        $m_content=$posts_tpl->fetch();
        $menu = $this->show_left_menu();

        $tpl = new Template(MODULE_ROOT.'/administration/view/layout.html');
        $tpl ->set('left_menu', $menu);
        $tpl ->set('content', $m_content);
        $tpl ->set('m', $m);
        //print_r($m);
        $content = $tpl ->fetch();
        return array('content'=>$content);
  }
  
  public function exec_create_group(){
      //This function create a new users
        $status = GET_value('s');
        $data['group_name'] = strtolower (POST_value('group_name',''));
        $data['group_description'] = POST_value('group_description','');
        $data['idcustomers'] = POST_value('idcustomers','');
        if ('submit' == $status){
            //Do insert stuff
            $r = Group :: create($data);
            if ($r['success']){
                $content='<div class="success" style="margin:10px">Group '.$data['group_name'].' is successfully created</div>';
                $index = $this->exec_view_group();
                $content.=$index['content'];
            }else{
                $content = '';
                if (!empty($r['error'])){ 
                    $content = '<div class="error" style="margin:10px">'.$r['error'].'</div>';
                }
                $content .= $this->show_gcreate_form($data, $r['error']);
            }
        }else{
            //Just show form
            $content = $this->show_gcreate_form($data, null);
        }
        
        return array('content'=>$content);
  }

public function exec_edit_group(){
    $status = GET_value('s');
        $group_id = (int) GET_value('group_id',0);
        if ('submit' == $status){
            $data['group_name'] = POST_value('group_name','');
            $data['group_description'] = POST_value('group_description','');
            $data['idcustomers'] = POST_value('idcustomers','');
            $r = Group :: update($group_id,$data);
            if ($r['success']){
                $content = '<div class="success">Group #'.$group_id.' is updated successfully!</div>';
//                $index = $this->exec_view_group();
//                $content.=$index['content']; 
                header('Location: index.php?m=administration&a=view_group');
            }else{
                $content='';
                //print_r($r);
                if (isset($r['error'])) $content .= '<div class="error">Something wrong! '.$r['error'].'</div>';
                $content .= $this->show_gedit_form($data, $r['error']);
            }
        }else{
            $r = Group :: get_group_data($group_id);
            if ($r['success']){
                $content = $this->show_gedit_form($r['data'], '');
            }else{
                $content = "<div class='error'>".$r['error'].'</div>';
            }
        }
        return array('content' => $content);
}

public function exec_delete_group(){
    $group_id = (int) GET_value('group_id',0);
        $r = Group :: delete($group_id);
        if ($r['success']){
            $content = '<div class="success">Delete user successful!</div>';
            $index = $this->exec_view_group();
            $content.=$index['content']; 
        }else{
            $content='';
            if (isset($r['error'])) $content .= '<div class="error">Something wrong! '.$r['error'].'</div>';
            $index = $this->exec_index();
            $content.=$index['content']; 
        }
        return array('content' => $content);
}

private function show_gcreate_form($data,$error){
//        $tpl = new Template(MODULE_ROOT.'/admin_groups/view/create_form.html');
//        $tpl ->set('data', $data);
//        $tpl ->set('error', $error);
//        return $tpl ->fetch();
           $m =  GET_value('m','administration');
        
       $posts_tpl = new Template(MODULE_ROOT.'/administration/view/gcreate_form.html');
        $posts_tpl ->set('data', $data);
        $posts_tpl ->set('error', $error);
        //return $tpl ->fetch();
        $m_content=$posts_tpl->fetch();
        $menu = $this->show_left_menu();

        $tpl = new Template(MODULE_ROOT.'/administration/view/layout.html');
        $tpl ->set('left_menu', $menu);
        $tpl ->set('content', $m_content);
        $tpl ->set('m', $m);
        //$content = $tpl ->fetch();
        return $tpl ->fetch();
    }
    
    private function show_gedit_form($data,$error){
//        $tpl = new Template(MODULE_ROOT.'/admin_groups/view/edit_form.html');
//        $tpl ->set('data', $data);
//        $tpl ->set('error', $error);
//        return $tpl ->fetch();
        
                   $m =  GET_value('m','administration');
        
       $posts_tpl = new Template(MODULE_ROOT.'/administration/view/gedit_form.html');
        $posts_tpl ->set('data', $data);
        $posts_tpl ->set('error', $error);
        //return $tpl ->fetch();
        $m_content=$posts_tpl->fetch();
        $menu = $this->show_left_menu();

        $tpl = new Template(MODULE_ROOT.'/administration/view/layout.html');
        $tpl ->set('left_menu', $menu);
        $tpl ->set('content', $m_content);
        $tpl ->set('m', $m);
        //$content = $tpl ->fetch();
        return $tpl ->fetch();
    }
    
    /* The below handle groups permission*/
    public function exec_permissions(){
        $m =  GET_value('m','administration');
        $group_id = GET_value('group_id');
        $status = GET_value('status','');
        $modules_permisions = Modules::get_modules_permissions();
        $default_permissions = Modules::get_default_permissions();
        
        $content = '';
        if ('submit'==$status){
            foreach($default_permissions as $per => $v){
                $permissions[$per] = isset($_POST[$per])? 1 : 0;
            }
            $r = Group :: set_permissions($group_id,$permissions);
            if ($r['success']){
                $content .= '<div class="success">Permissions has been set succesfully!</div>';
            }else{
                $content .= '<div class="success">'.$r['error'].'</div>';                
            }
            
        }else{
            //
            //Real permissions (must compare with DB values)
            $r = Group :: get_permissions($group_id);
            if ($r['success']){
                $permissions = $r['permissions']; //Need to merge with default_permission, incase modules change
                //print_r($permissions);
            }else{
                $content .='<div class="info">'.$r['error'].'</div>';
                $permissions = $default_permissions;                            
            }
        }
        
        
        //Show form
        $posts_tpl = new Template(MODULE_ROOT.'/administration/view/permissions_form.html');
        $posts_tpl ->set('permissions', $permissions);
        $posts_tpl ->set('modules_permissions', $modules_permisions);
        $posts_tpl ->set('group_id', $group_id);
        $m_content=$posts_tpl->fetch();
        $menu = $this->show_left_menu();
        
        $tpl = new Template(MODULE_ROOT.'/administration/view/layout.html');
        $tpl ->set('left_menu', $menu);
        $tpl ->set('content', $m_content);
        $tpl ->set('m', $m);
        //print_r($m);
        $content .= $tpl ->fetch();
        return array('content'=>$content);
    }
}
